//
//  DrapesController.m
//  GKBHouse
//
//  Created by  on 12-7-1.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "DrapesController.h"
#import "GKBNavigationBar.h"
#import "DeviceView.h"
#import "iToast.h"
#import "LoginController1.h"


@implementation DrapesController
@synthesize equipment;
@synthesize order;
@synthesize autoStopAnimation;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (id)initWithEquipment:(NewEquipment *)equ
{
    self = [super init];
    if (self) {
        self.equipment = equ;
        
    }
    return self;
}
- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    [self.view setFrame:CGRectMake(0, 0, DEVICE_HEIGHT, DEVICE_WIDTH)];
    
    [self initTopBar];
    
    [open setTitle:NSLocalizedString(@"drapOpen", nil) forState:UIControlStateNormal];
    [open addTarget:self action:@selector(openDrapes) forControlEvents:UIControlEventTouchUpInside];
    [stop setTitle:NSLocalizedString(@"pause", nil) forState:UIControlStateNormal];
    [stop addTarget:self action:@selector(stopDrapes) forControlEvents:UIControlEventTouchUpInside];
    [close setTitle:NSLocalizedString(@"drapClose", nil) forState:UIControlStateNormal];
    [close addTarget:self action:@selector(closeDrapes) forControlEvents:UIControlEventTouchUpInside];
    
    totalTime = 30.0;
    if([self.equipment.state isEqualToString:kStateON])
    {
        timeIndex = 1;
        //[mainImageView setImage:[UIImage imageNamed:@"window.png"]];
        [self showDrapes: timeIndex/totalTime];
    }
    if([self.equipment.state isEqualToString: kStateOFF])
    {
        timeIndex = 30;
      //  [mainImageView setImage:[UIImage imageNamed:@"draps.png"]];
        [self showDrapes: timeIndex/totalTime];
    }

    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

//- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
//{
//    // Return YES for supported orientations
//    return (interfaceOrientation == UIInterfaceOrientationPortrait);
//}
- (void)initTopBar
{    
    GKBNavigationBar *topBar = [[GKBNavigationBar alloc]init];
    [topBar setTarget:self returnAction:@selector(closeView) withTitle:self.equipment.name];
    [self.view addSubview:topBar];    
    [topBar release];
    
}
- (void)closeView
{
    [self stopTimer];
    [GKBMainController refreshDevices];
    [self.view removeFromSuperview];
    [GKBMainController postStartRefresh];
}
- (void)showDrapes:(float)progress
{
    CGRect frame = mainImageView.frame;
    frame.size.width = 320.0*progress;
    [mainImageView setFrame:frame];
}
- (void)openAnimating
{
    if (timeIndex > 1) {
        timeIndex--;
        NSTimer *time = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(openAnimating) userInfo:nil repeats:NO];
        [self stopTimer];
        self.autoStopAnimation = time;
    }
    
    [self showDrapes: timeIndex/totalTime];
    
}
- (void)closeAnimating
{
    
    if (timeIndex >= totalTime) {
       self.equipment.state = kStateOFF;
    }
    else
    {
       // timeIndex++;
        NSTimer *time = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(closeAnimating) userInfo:nil repeats:NO];
        [self stopTimer];
        self.autoStopAnimation = time;
        timeIndex++;        
    }
    [self showDrapes: timeIndex/totalTime];
}
- (void)stopAnimating
{
    [self stopTimer];
   // [mainImageView stopAnimating];
}

- (void)openAnimatingEnd
{
    [mainImageView stopAnimating];
    [mainImageView setImage:[UIImage imageNamed:@"windowStop3.png"]];
}
- (void)closeAnimatingEnd
{
    self.equipment.state = kStateOFF;
    [mainImageView stopAnimating];
    [mainImageView setImage:[UIImage imageNamed:@"windowStop1.png"]];
}
- (void)setAnimationEnd:(SEL)action
{
    [self stopTimer];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:self forKey:@"target"];
    [dic setValue:NSStringFromSelector(action) forKey:@"selector"];
    NSTimer *time = [NSTimer scheduledTimerWithTimeInterval:120 target:self selector:@selector(AnimationDidStop:) userInfo:dic repeats:NO];
    
    self.autoStopAnimation = time;
}
- (void)AnimationDidStop:(NSTimer *)timer
{
    NSDictionary *dic = timer.userInfo;
    id target = [dic objectForKey:@"target"];
    SEL selector = NSSelectorFromString([dic objectForKey:@"selector"]) ;
    if (target && selector) {
        [target performSelector:selector];
    }
}
- (void)stopTimer
{
    if ([self.autoStopAnimation isValid]) {
        [self.autoStopAnimation invalidate];
        self.autoStopAnimation = nil;
    }
}
#pragma mark - 电器设备开关状态
- (void)openDrapes
{
//    [self openAnimating];
//    return;
    [self ctlDevice:@"OPEN"];
}
- (void)closeDrapes
{
//    [self closeAnimating];
//    return;
    [self ctlDevice:@"CLOSE"];
}
- (void)stopDrapes
{
//    [self stopAnimating];
//    return;
    [self ctrStopDrapes];
}
- (void)ctlDevice:(NSString *)aOrder
{
    BOOL OPEN = NO;
    if ([aOrder isEqualToString:@"OPEN"]) {
        OPEN = YES;
    }
    if ([aOrder isEqualToString:@"CLOSE"]) {
        OPEN = NO;
    }
    self.order = aOrder;
    NSString *switchId = self.equipment.switchId;
    NSString *name = self.equipment.name;

    [DeviceView OperatSwithcId:switchId name:name OnOff:OPEN target:self end:@selector(ctlDeviceEnd:)];
}
- (void)ctlDeviceEnd:(NSDictionary *)dic
{
    NSLog(@"%@", dic);
    BOOL OPEN = NO;
    if ([self.order isEqualToString:@"OPEN"]) {
        OPEN = YES;
    }
    if ([self.order isEqualToString:@"CLOSE"]) {
        OPEN = NO;
    }
    
   // NSString *tip = [DeviceView ctlDeviceStr:OPEN name:self.equipment.name];
    
    
    NSNumber *result = [dic objectForKey:@"result"];
    if (result.integerValue == 0) {   
        //操作成功 
        NSString *success = [OperationTip operatSuccess:YES type:ErrorTypeServerReturnFail];
        [iToast showTip:success gravity:iToastGravityBottom];
        [self setViewState:self.order];
        
        GKBMainController *main = [GKBMainController mainCtr];
        [main updateStateByNet];
    }
    else
    {
        //操作失败！原因：
        NSString *fail = [OperationTip operatSuccess:NO type:ErrorTypeServerReturnFail];
        [iToast showTip:fail gravity:iToastGravityBottom];
    }
    
}
- (void)setViewState:(NSString *)aOrder
{
    if ([aOrder isEqualToString:@"OPEN"]) {
        self.equipment.state = kStateON;
        //[mainImageView setImage:[UIImage imageNamed:@"windowStop3.png"]];
        timeIndex = totalTime;
        [self openAnimating];
    }
    if ([aOrder isEqualToString:@"CLOSE"]) {
        //2分钟后才关
        //self.equipment.state = kStateOFF;
        timeIndex = 1;
        [self closeAnimating];
    }
    if ([aOrder isEqualToString:@"STOP"]) {
        //暂停不改变状态
        
        [self stopAnimating];
    }

}

- (void)ctrStopDrapesEnd:(NSDictionary *)dic
{
    NSLog(@"%@", dic);
    NSNumber *result = [dic objectForKey:@"result"];
 //   NSString *tipStart = [NSString stringWithFormat:@"%@:%@", self.equipment.name, NSLocalizedString(@"pause", nil)];
    if (result.integerValue == 0) {        
        //[self setViewState:self.order];
        //操作成功 
        NSString *tip = [OperationTip operatSuccess:YES type:ErrorTypeServerReturnFail];
        [iToast showTip:tip gravity:iToastGravityBottom];
        [self setViewState:@"STOP"];
        
        GKBMainController *main = [GKBMainController mainCtr];
        [main updateStateByNet];
    }
    else
    {
        //操作失败！原因：
        NSString *tip = [OperationTip operatSuccess:NO type:ErrorTypeServerReturnFail];
        [iToast showTip:tip gravity:iToastGravityBottom];
    }
}
@end
